﻿using Angle.Krill.SystemConfig;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Angle.Krill.Utils
{
    public class WallpaperHelper
    {
        private readonly string configPath = Path.Combine(Application.StartupPath, "Configs/wallpaper.json");
        private List<WallpaperInfo> wallpaperInfos = null;
        private IntPtr desktopWindowHandle;
        private WinWallpaper winWallpaper;
        private WebView2 webView;

        private readonly static object obj = new object();
        private volatile static WallpaperHelper instance;

        private WallpaperHelper() { }
        /// <summary>
        /// 缓存
        /// </summary>
        public static WallpaperHelper Instance
        {
            get
            {
                if (null == instance)
                {
                    lock (obj)
                    {
                        instance = new WallpaperHelper();
                    }
                }

                return instance;
            }
        }

        public List<WallpaperInfo> WallpaperInfos
        {
            get
            {
                if (null == wallpaperInfos)
                {
                    this.wallpaperInfos = JsonConvert.DeserializeObject<List<WallpaperInfo>>(File.ReadAllText(this.configPath));
                }

                return this.wallpaperInfos;
            }
        }

        public WinWallpaper CurWinWallpaper
        {
            get
            {
                return this.winWallpaper;
            }
        }

        /// <summary>
        /// 刷新壁纸信息
        /// </summary>
        /// <returns></returns>
        public List<WallpaperInfo> RefreshWallpaperInfos()
        {
            this.wallpaperInfos = JsonConvert.DeserializeObject<List<WallpaperInfo>>(File.ReadAllText(this.configPath));

            return this.wallpaperInfos;
        }

        public void LoadWallpaper(WallpaperInfo wInfo)
        {
            if (this.winWallpaper == null)
            {
                this.InitDesktopWebView();
            }

            this.SetUri(wInfo.Url);

            SysConfigHelper.Instance.SysConfig.WallpaperInfo = wInfo;

            SysConfigHelper.Instance.SaveSysConfig();
        }

        internal void SetUri(string path)
        {
            this.webView.Source = new Uri(path);
        }

        /// <summary>
        /// 初始化壁纸桌面视图
        /// </summary>
        private void InitDesktopWebView()
        {
            this.desktopWindowHandle = NativeMethods.DS2_GetDesktopWindowHandle();
            InitWebView();

            InitializeCoreWebView2EnvironmentAsync();
            this.winWallpaper = new WinWallpaper();
            this.winWallpaper.SetParam(this.webView, Screen.PrimaryScreen.Bounds);
            this.winWallpaper.Show();
            NativeMethods.SetParent(winWallpaper.Handle, this.desktopWindowHandle);

            this.ForwardMessage();
        }

        private void InitWebView()
        {
            if (this.webView == null)
            {
                this.webView = new WebView2();
            }

            this.webView.Dock = DockStyle.Fill;
        }

        private void ForwardMessage()
        {
            IntPtr hWnd = this.GetMessageHandle();
            if (hWnd != IntPtr.Zero)
                NativeMethods.DS2_StartForwardMouseKeyboardMessage(hWnd);
        }

        public IntPtr GetMessageHandle()
        {
            IntPtr chrome_WidgetWin_0 = NativeMethods.FindWindowEx(this.webView.Handle, IntPtr.Zero, "Chrome_WidgetWin_0", null);
            if (chrome_WidgetWin_0 == IntPtr.Zero)
                return IntPtr.Zero;

            return NativeMethods.FindWindowEx(chrome_WidgetWin_0, IntPtr.Zero, "Chrome_WidgetWin_1", null);
        }

        private async void InitializeCoreWebView2EnvironmentAsync()
        {
            string args = "--autoplay-policy=no-user-gesture-required ";
            //if (_webWindowOptions.DisableWebSecurity)
            args += "--disable-web-security";

            CoreWebView2Environment coreWebView2Environment = await CoreWebView2Environment.CreateAsync(null, FileHelper.GetPathForUserAppDataFolder(), new CoreWebView2EnvironmentOptions(args));
            await this.webView.EnsureCoreWebView2Async(coreWebView2Environment);
            this.webView.CoreWebView2.IsMuted = false;
            this.webView.CoreWebView2.MemoryUsageTargetLevel = CoreWebView2MemoryUsageTargetLevel.Low;

            string script = File.ReadAllText(FileHelper.GetPathForStartupFolder("Wallpaper\\script.js"));
            await this.webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script);
        }
    }
}
